<template>
  <div class="orders">
    <!-- 搜索表单 -->
    <el-card class="search-form">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户姓名" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待付款" value="pending" />
            <el-option label="已付款" value="paid" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增订单
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
      <el-button type="success" @click="handleExport">
        <el-icon><Download /></el-icon>
        导出订单
      </el-button>
    </div>

    <!-- 订单表格 -->
    <el-card class="table-container">
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="customerPhone" label="联系电话" width="130" />
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="scope">
            <span style="color: #f56c6c; font-weight: bold;">¥{{ scope.row.totalAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100">
          <template #default="scope">
            <el-tag type="info" size="small">
              {{ getPaymentMethodName(scope.row.paymentMethod) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button type="info" size="small" @click="viewOrder(scope.row)">查看</el-button>
            <el-button type="primary" size="small" @click="editOrder(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteOrder(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="resetForm"
    >
      <el-form
        ref="orderFormRef"
        :model="orderForm"
        :rules="rules"
        label-width="100px"
        class="dialog-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="customerName">
              <el-input v-model="orderForm.customerName" placeholder="请输入客户姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="customerPhone">
              <el-input v-model="orderForm.customerPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单金额" prop="totalAmount">
              <el-input-number v-model="orderForm.totalAmount" :min="0" :precision="2" placeholder="请输入订单金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="orderForm.paymentMethod" placeholder="请选择支付方式">
                <el-option label="微信支付" value="wechat" />
                <el-option label="支付宝" value="alipay" />
                <el-option label="银行卡" value="bank" />
                <el-option label="现金" value="cash" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="收货地址" prop="address">
          <el-input
            v-model="orderForm.address"
            type="textarea"
            :rows="2"
            placeholder="请输入收货地址"
          />
        </el-form-item>
        <el-form-item label="订单备注" prop="remark">
          <el-input
            v-model="orderForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入订单备注"
          />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-radio-group v-model="orderForm.status">
            <el-radio label="pending">待付款</el-radio>
            <el-radio label="paid">已付款</el-radio>
            <el-radio label="shipped">已发货</el-radio>
            <el-radio label="completed">已完成</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="订单详情"
      width="600px"
    >
      <div class="order-detail" v-if="currentOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ getStatusName(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ currentOrder.customerName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentOrder.customerPhone }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">
            <span style="color: #f56c6c; font-weight: bold;">¥{{ currentOrder.totalAmount }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">
            {{ getPaymentMethodName(currentOrder.paymentMethod) }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ currentOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="收货地址" :span="2">{{ currentOrder.address }}</el-descriptions-item>
          <el-descriptions-item label="订单备注" :span="2">{{ currentOrder.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 状态更新对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      title="更新订单状态"
      width="400px"
    >
      <el-form label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(currentOrder?.status)">
            {{ getStatusName(currentOrder?.status) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select v-model="newStatus" placeholder="请选择新状态">
            <el-option label="待付款" value="pending" />
            <el-option label="已付款" value="paid" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmUpdateStatus">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'Orders',
  setup() {
    const loading = ref(false)
    const dialogVisible = ref(false)
    const viewDialogVisible = ref(false)
    const statusDialogVisible = ref(false)
    const isEdit = ref(false)
    const dialogTitle = ref('新增订单')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const multipleSelection = ref([])
    const orderFormRef = ref()
    const currentOrder = ref(null)
    const newStatus = ref('')

    // 搜索表单
    const searchForm = reactive({
      orderNo: '',
      customerName: '',
      status: '',
      dateRange: []
    })

    // 订单表单
    const orderForm = reactive({
      id: null,
      orderNo: '',
      customerName: '',
      customerPhone: '',
      totalAmount: 0,
      paymentMethod: '',
      address: '',
      remark: '',
      status: 'pending'
    })

    // 表单验证规则
    const rules = {
      customerName: [
        { required: true, message: '请输入客户姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      customerPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      totalAmount: [
        { required: true, message: '请输入订单金额', trigger: 'blur' },
        { type: 'number', min: 0.01, message: '订单金额必须大于0', trigger: 'blur' }
      ],
      paymentMethod: [
        { required: true, message: '请选择支付方式', trigger: 'change' }
      ],
      address: [
        { required: true, message: '请输入收货地址', trigger: 'blur' },
        { min: 10, max: 200, message: '地址长度在 10 到 200 个字符', trigger: 'blur' }
      ]
    }

    // 模拟数据
    const mockData = [
      {
        id: 1,
        orderNo: 'ORD202401001',
        customerName: '张三',
        customerPhone: '13800138001',
        totalAmount: 299.00,
        paymentMethod: 'wechat',
        address: '北京市朝阳区某某街道某某小区1号楼101室',
        remark: '请尽快发货',
        status: 'paid',
        createTime: '2024-01-01 10:00:00'
      },
      {
        id: 2,
        orderNo: 'ORD202401002',
        customerName: '李四',
        customerPhone: '13800138002',
        totalAmount: 1299.00,
        paymentMethod: 'alipay',
        address: '上海市浦东新区某某路某某号',
        remark: '',
        status: 'shipped',
        createTime: '2024-01-02 14:30:00'
      },
      {
        id: 3,
        orderNo: 'ORD202401003',
        customerName: '王五',
        customerPhone: '13800138003',
        totalAmount: 89.00,
        paymentMethod: 'bank',
        address: '广州市天河区某某大道某某广场',
        remark: '周末配送',
        status: 'completed',
        createTime: '2024-01-03 09:15:00'
      },
      {
        id: 4,
        orderNo: 'ORD202401004',
        customerName: '赵六',
        customerPhone: '13800138004',
        totalAmount: 599.00,
        paymentMethod: 'wechat',
        address: '深圳市南山区某某科技园',
        remark: '公司地址',
        status: 'pending',
        createTime: '2024-01-04 16:45:00'
      },
      {
        id: 5,
        orderNo: 'ORD202401005',
        customerName: '钱七',
        customerPhone: '13800138005',
        totalAmount: 199.00,
        paymentMethod: 'cash',
        address: '杭州市西湖区某某路某某小区',
        remark: '货到付款',
        status: 'cancelled',
        createTime: '2024-01-05 11:20:00'
      }
    ]

    const tableData = ref([])

    // 获取状态名称
    const getStatusName = (status) => {
      const statusMap = {
        pending: '待付款',
        paid: '已付款',
        shipped: '已发货',
        completed: '已完成',
        cancelled: '已取消'
      }
      return statusMap[status] || status
    }

    // 获取状态标签类型
    const getStatusType = (status) => {
      const typeMap = {
        pending: 'warning',
        paid: 'primary',
        shipped: 'info',
        completed: 'success',
        cancelled: 'danger'
      }
      return typeMap[status] || 'default'
    }

    // 获取支付方式名称
    const getPaymentMethodName = (method) => {
      const methodMap = {
        wechat: '微信支付',
        alipay: '支付宝',
        bank: '银行卡',
        cash: '现金'
      }
      return methodMap[method] || method
    }

    // 生成订单号
    const generateOrderNo = () => {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const random = String(Math.floor(Math.random() * 1000)).padStart(3, '0')
      return `ORD${year}${month}${day}${random}`
    }

    // 获取订单列表
    const getOrderList = () => {
      loading.value = true
      // 模拟API请求
      setTimeout(() => {
        let filteredData = [...mockData]
        
        // 搜索过滤
        if (searchForm.orderNo) {
          filteredData = filteredData.filter(item => 
            item.orderNo.includes(searchForm.orderNo)
          )
        }
        if (searchForm.customerName) {
          filteredData = filteredData.filter(item => 
            item.customerName.includes(searchForm.customerName)
          )
        }
        if (searchForm.status) {
          filteredData = filteredData.filter(item => 
            item.status === searchForm.status
          )
        }
        if (searchForm.dateRange && searchForm.dateRange.length === 2) {
          filteredData = filteredData.filter(item => {
            const createDate = item.createTime.split(' ')[0]
            return createDate >= searchForm.dateRange[0] && createDate <= searchForm.dateRange[1]
          })
        }

        total.value = filteredData.length
        
        // 分页
        const start = (currentPage.value - 1) * pageSize.value
        const end = start + pageSize.value
        tableData.value = filteredData.slice(start, end)
        
        loading.value = false
      }, 500)
    }

    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      getOrderList()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        orderNo: '',
        customerName: '',
        status: '',
        dateRange: []
      })
      handleSearch()
    }

    // 新增订单
    const handleAdd = () => {
      isEdit.value = false
      dialogTitle.value = '新增订单'
      orderForm.orderNo = generateOrderNo()
      dialogVisible.value = true
    }

    // 查看订单详情页面
     const viewOrder = (row) => {
       router.push({
         path: '/detail',
         query: {
           type: 'order',
           id: row.id,
           action: 'view'
         }
       })
     }

    // 编辑订单
     const editOrder = (row) => {
       isEdit.value = true
       dialogTitle.value = '编辑订单'
       Object.assign(orderForm, { ...row })
       dialogVisible.value = true
     }
     
     // 删除订单
     const deleteOrder = (id) => {
       ElMessageBox.confirm('确定要删除这个订单吗？', '提示', {
         confirmButtonText: '确定',
         cancelButtonText: '取消',
         type: 'warning'
       }).then(() => {
         const index = orders.value.findIndex(order => order.id === id)
         if (index > -1) {
           orders.value.splice(index, 1)
           ElMessage.success('删除成功')
         }
       })
     }

    // 编辑订单
    const handleEdit = (row) => {
      isEdit.value = true
      dialogTitle.value = '编辑订单'
      Object.assign(orderForm, { ...row })
      dialogVisible.value = true
    }

    // 查看订单
    const handleView = (row) => {
      currentOrder.value = { ...row }
      viewDialogVisible.value = true
    }

    // 更新状态
    const handleUpdateStatus = (row) => {
      currentOrder.value = { ...row }
      newStatus.value = row.status
      statusDialogVisible.value = true
    }

    // 确认更新状态
    const confirmUpdateStatus = () => {
      if (!newStatus.value) {
        ElMessage.warning('请选择新状态')
        return
      }
      
      // 模拟更新状态操作
      const index = mockData.findIndex(item => item.id === currentOrder.value.id)
      if (index > -1) {
        mockData[index].status = newStatus.value
        getOrderList()
        ElMessage.success('状态更新成功')
        statusDialogVisible.value = false
      }
    }

    // 删除订单
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除订单 "${row.orderNo}" 吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 模拟删除操作
        const index = mockData.findIndex(item => item.id === row.id)
        if (index > -1) {
          mockData.splice(index, 1)
          getOrderList()
          ElMessage.success('删除成功')
        }
      })
    }

    // 批量删除
    const handleBatchDelete = () => {
      ElMessageBox.confirm(
        `确定要删除选中的 ${multipleSelection.value.length} 个订单吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 模拟批量删除操作
        multipleSelection.value.forEach(item => {
          const index = mockData.findIndex(data => data.id === item.id)
          if (index > -1) {
            mockData.splice(index, 1)
          }
        })
        getOrderList()
        ElMessage.success('批量删除成功')
      })
    }

    // 导出订单
    const handleExport = () => {
      ElMessage.success('导出功能开发中...')
    }

    // 选择改变
    const handleSelectionChange = (val) => {
      multipleSelection.value = val
    }

    // 分页大小改变
    const handleSizeChange = (val) => {
      pageSize.value = val
      getOrderList()
    }

    // 当前页改变
    const handleCurrentChange = (val) => {
      currentPage.value = val
      getOrderList()
    }

    // 提交表单
    const submitForm = () => {
      orderFormRef.value.validate((valid) => {
        if (valid) {
          if (isEdit.value) {
            // 编辑订单
            const index = mockData.findIndex(item => item.id === orderForm.id)
            if (index > -1) {
              Object.assign(mockData[index], { ...orderForm })
              ElMessage.success('编辑成功')
            }
          } else {
            // 新增订单
            const newOrder = {
              ...orderForm,
              id: Date.now(),
              createTime: new Date().toLocaleString()
            }
            mockData.unshift(newOrder)
            ElMessage.success('新增成功')
          }
          dialogVisible.value = false
          getOrderList()
        }
      })
    }

    // 重置表单
    const resetForm = () => {
      Object.assign(orderForm, {
        id: null,
        orderNo: '',
        customerName: '',
        customerPhone: '',
        totalAmount: 0,
        paymentMethod: '',
        address: '',
        remark: '',
        status: 'pending'
      })
      if (orderFormRef.value) {
        orderFormRef.value.clearValidate()
      }
    }

    onMounted(() => {
      getOrderList()
    })

    return {
      loading,
      dialogVisible,
      viewDialogVisible,
      statusDialogVisible,
      isEdit,
      dialogTitle,
      currentPage,
      pageSize,
      total,
      multipleSelection,
      orderFormRef,
      currentOrder,
      newStatus,
      searchForm,
      orderForm,
      rules,
      tableData,
      getStatusName,
      getStatusType,
      getPaymentMethodName,
      handleSearch,
      resetSearch,
      handleAdd,
       viewOrder,
       editOrder,
       deleteOrder,
       handleEdit,
      handleView,
      handleUpdateStatus,
      confirmUpdateStatus,
      handleDelete,
      handleBatchDelete,
      handleExport,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      submitForm,
      resetForm
    }
  }
}
</script>

<style scoped>
.orders {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.operation-buttons {
  margin-bottom: 20px;
}

.table-container {
  background: white;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-form .el-form-item {
  margin-bottom: 20px;
}

.order-detail {
  padding: 10px 0;
}
</style>